<template>
  <div class="ai-model-list">
    <div class="component-header">
      <el-button type="primary" @click="showAddModelDialog">添加模型</el-button>
    </div>
    
    <!-- 添加加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    
    <!-- 添加错误提示 -->
    <el-alert
      v-if="error"
      title="加载失败"
      type="error"
      :description="error"
      show-icon
      :closable="false"
      style="margin-bottom: 16px;"
    />
    
    <el-table v-else :data="models" style="width: 100%">
      <el-table-column prop="name" label="模型名称" />
      <el-table-column prop="provider" label="提供商" />
      <el-table-column prop="model_id" label="模型 ID" />
      <el-table-column prop="description" label="描述" show-overflow-tooltip />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.is_active ? 'success' : 'info'">
            {{ scope.row.is_active ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button-group>
            <el-button size="small" @click="editModel(scope.row)">编辑</el-button>
            <el-button size="small" type="primary" @click="testModel(scope.row)">测试</el-button>
            <el-button 
              size="small" 
              :type="scope.row.is_active ? 'warning' : 'success'"
              @click="toggleModelStatus(scope.row)"
            >
              {{ scope.row.is_active ? '禁用' : '启用' }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteModel(scope.row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 添加/编辑模型对话框 -->
    <el-dialog 
      :title="isEdit ? '编辑 AI 模型' : '添加 AI 模型'" 
      v-model="dialogVisible"
      width="600px"
    >
      <el-form :model="modelForm" label-width="120px" :rules="rules" ref="modelFormRef">
        <el-form-item label="模型名称" prop="name">
          <el-input v-model="modelForm.name" placeholder="给模型起个名字，如 GPT-4-Turbo" />
        </el-form-item>
        
        <el-form-item label="提供商" prop="provider">
          <el-select v-model="modelForm.provider" placeholder="选择 AI 提供商" style="width: 100%">
            <el-option label="OpenAI" value="OpenAI" />
            <el-option label="Anthropic" value="Anthropic" />
            <el-option label="Google" value="Google" />
            <el-option label="Mistral" value="Mistral" />
            <el-option label="其他" value="Other" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="API 类型" prop="api_type">
          <el-select 
            v-model="modelForm.api_type" 
            placeholder="选择 API 类型" 
            style="width: 100%"
          >
            <el-option label="OpenAI 兼容" value="openai" />
            <el-option label="Anthropic" value="anthropic" />
            <el-option label="Google" value="google" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="模型 ID" prop="model_id">
          <el-input 
            v-model="modelForm.model_id" 
            placeholder="输入模型 ID，例如 gpt-4-turbo-preview"
          />
          <div class="form-tip">
            输入模型提供商支持的模型 ID，例如 OpenAI 的 gpt-4-turbo-preview 或 Anthropic 的 claude-3-opus-20240229
          </div>
        </el-form-item>
        
        <el-form-item label="API 密钥" prop="api_key">
          <el-input 
            v-model="modelForm.api_key" 
            placeholder="输入 API 密钥" 
            type="password" 
            show-password
          />
        </el-form-item>
        
        <el-form-item label="API 端点" prop="api_endpoint">
          <el-input 
            v-model="modelForm.api_endpoint" 
            placeholder="可选，如 https://api.openai.com/v1"
          />
          <div class="form-tip">留空则使用默认端点</div>
        </el-form-item>
        
        <el-form-item label="API 版本" prop="api_version">
          <el-input 
            v-model="modelForm.api_version" 
            placeholder="可选，如 2023-05-15"
          />
          <div class="form-tip">留空则使用默认版本</div>
        </el-form-item>
        
        <el-form-item label="最大 Token" prop="max_tokens">
          <el-input-number 
            v-model="modelForm.max_tokens" 
            :min="1" 
            :max="100000" 
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="默认温度" prop="temperature_default">
          <el-slider 
            v-model="modelForm.temperature_default" 
            :min="0" 
            :max="2" 
            :step="0.1" 
            show-input
          />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="modelForm.description" 
            type="textarea" 
            :rows="3" 
            placeholder="描述这个模型的特点和用途"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="is_active">
          <el-switch 
            v-model="modelForm.is_active" 
            active-text="启用" 
            inactive-text="禁用"
          />
        </el-form-item>
        
        <el-form-item label="流式输出" prop="stream_enabled">
          <el-switch 
            v-model="modelForm.stream_enabled" 
            active-text="启用" 
            inactive-text="禁用"
          />
          <div class="form-tip">
            启用流式输出可以实时显示 AI 生成的内容，提供更好的用户体验
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveModel" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- 测试模型对话框 -->
    <el-dialog 
      title="测试 AI 模型" 
      v-model="testDialogVisible"
      width="600px"
    >
      <div class="test-form">
        <el-form :model="testForm" label-width="80px">
          <el-form-item label="测试消息">
            <el-input 
              v-model="testForm.message" 
              type="textarea" 
              :rows="3"
              placeholder="输入测试消息"
            />
          </el-form-item>
        </el-form>
        
        <div class="dialog-footer">
          <el-button @click="testDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="runModelTest" 
            :loading="testing"
          >
            发送测试
          </el-button>
          <el-button 
            type="success" 
            @click="runStreamTest" 
            :loading="streaming"
            v-if="currentTestModel && currentTestModel.stream_enabled"
          >
            流式测试
          </el-button>
        </div>
      </div>
      
      <div v-if="testResult" class="test-result">
        <h4>测试结果:</h4>
        <pre>{{ testResult }}</pre>
      </div>
      
      <div v-if="fullStreamResult" class="test-result stream-result">
        <h4>流式测试结果:</h4>
        <pre class="typewriter-text">{{ fullStreamResult }}<span class="cursor" v-if="streaming"></span></pre>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { fetchAIModels, fetchAIModel, createAIModel, updateAIModel, deleteAIModel, testAIModel, streamTestAIModel } from '../api/ai_model'

// 模型列表
const models = ref([])
const loading = ref(false)
const error = ref('')

// 对话框控制
const dialogVisible = ref(false)
const isEdit = ref(false)
const saving = ref(false)

// 测试对话框
const testDialogVisible = ref(false)
const currentTestModel = ref(null)
const testForm = ref({ message: '' })
const testResult = ref('')
const testing = ref(false)
const streaming = ref(false)
const fullStreamResult = ref('')

// 表单引用
const modelFormRef = ref(null)

// 模型表单数据
const modelForm = reactive({
  id: '',
  name: '',
  provider: '',
  model_id: '',
  api_type: '',
  description: '',
  max_tokens: 4096,
  temperature_default: 0.7,
  api_key: '',
  api_endpoint: '',
  api_version: '',
  stream_enabled: true,
  is_active: true
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入模型名称', trigger: 'blur' }],
  provider: [{ required: true, message: '请选择提供商', trigger: 'change' }],
  api_type: [{ required: true, message: '请选择 API 类型', trigger: 'change' }],
  model_id: [{ required: true, message: '请输入模型 ID', trigger: 'blur' }],
  api_key: [{ required: true, message: '请输入 API 密钥', trigger: 'blur' }]
}

// 加载模型列表
const loadModels = async () => {
  try {
    loading.value = true
    error.value = ''
    models.value = await fetchAIModels()
  } catch (err) {
    console.error('加载模型失败', err)
    error.value = err.message || '加载模型失败，请检查网络连接和后端服务'
    ElMessage.error('加载模型失败')
  } finally {
    loading.value = false
  }
}

// 显示添加模型对话框
const showAddModelDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑模型
const editModel = async (model) => {
  try {
    isEdit.value = true
    const fullModel = await fetchAIModel(model.id)
    
    // 填充表单
    Object.keys(modelForm).forEach(key => {
      if (key in fullModel) {
        modelForm[key] = fullModel[key]
      }
    })
    
    dialogVisible.value = true
  } catch (error) {
    console.error('加载模型详情失败', error)
    ElMessage.error('加载模型详情失败')
  }
}

// 保存模型
const saveModel = () => {
  modelFormRef.value.validate(async (valid) => {
    if (!valid) {
      return
    }
    
    try {
      saving.value = true
      
      // 准备数据
      const modelData = { ...modelForm }
      
      if (isEdit.value) {
        // 更新现有模型
        await updateAIModel(modelForm.id, modelData)
        ElMessage.success('模型更新成功')
      } else {
        // 创建新模型
        await createAIModel(modelData)
        ElMessage.success('模型添加成功')
      }
      
      dialogVisible.value = false
      loadModels()
    } catch (error) {
      console.error('保存模型失败', error)
      ElMessage.error('保存模型失败: ' + (error.response?.data?.detail || error.message))
    } finally {
      saving.value = false
    }
  })
}

// 删除模型
const deleteModel = async (model) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除模型 "${model.name}" 吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteAIModel(model.id)
    ElMessage.success('模型已删除')
    loadModels()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除模型失败', error)
      ElMessage.error('删除模型失败')
    }
  }
}

// 切换模型状态
const toggleModelStatus = async (model) => {
  try {
    const updatedModel = { ...model, is_active: !model.is_active }
    await updateAIModel(model.id, updatedModel)
    ElMessage.success(`模型已${updatedModel.is_active ? '启用' : '禁用'}`)
    loadModels()
  } catch (error) {
    console.error('更新模型状态失败', error)
    ElMessage.error('更新模型状态失败')
  }
}

// 测试模型
const testModel = (model) => {
  currentTestModel.value = model
  testForm.value.message = '你好，请介绍一下你自己。'
  testResult.value = ''
  testDialogVisible.value = true
}

// 运行模型测试
const runModelTest = async () => {
  if (!currentTestModel.value || !testForm.value.message.trim()) {
    ElMessage.warning('请输入测试消息')
    return
  }
  
  try {
    testing.value = true
    const result = await testAIModel(currentTestModel.value.id, testForm.value.message)
    testResult.value = result.response
  } catch (error) {
    console.error('测试模型失败', error)
    testResult.value = `测试失败: ${error.response?.data?.detail || error.message}`
  } finally {
    testing.value = false
  }
}

// 简化流式测试方法
const runStreamTest = async () => {
  if (!currentTestModel.value || !testForm.value.message.trim()) {
    ElMessage.warning('请输入测试消息')
    return
  }
  
  try {
    streaming.value = true
    fullStreamResult.value = ''
    
    await streamTestAIModel(
      currentTestModel.value.id, 
      testForm.value.message,
      // 处理每个文本块
      (chunk) => {
        console.log('收到流式内容:', chunk)
        fullStreamResult.value += chunk
      },
      // 处理错误
      (error) => {
        console.error('流式测试失败', error)
        ElMessage.error(`流式测试失败: ${error.message}`)
      },
      // 完成回调
      () => {
        streaming.value = false
      }
    )
  } catch (error) {
    console.error('流式测试失败', error)
    ElMessage.error(`流式测试失败: ${error.message}`)
    streaming.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (modelFormRef.value) {
    modelFormRef.value.resetFields()
  }
  
  Object.assign(modelForm, {
    id: '',
    name: '',
    provider: '',
    model_id: '',
    api_type: '',
    description: '',
    max_tokens: 4096,
    temperature_default: 0.7,
    api_key: '',
    api_endpoint: '',
    api_version: '',
    stream_enabled: true,
    is_active: true
  })
}

// 在组件卸载时停止打字效果
onUnmounted(() => {
  streaming.value = false
})

onMounted(() => {
  loadModels()
})
</script>

<style scoped>
.ai-model-list {
  width: 100%;
}

.component-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.test-form {
  margin-bottom: 16px;
}

.test-result {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
  margin-top: 16px;
}

.test-result h4 {
  margin-top: 0;
  margin-bottom: 8px;
  color: #303133;
}

.test-result pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
}

.stream-result {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
}

.typewriter-text {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
  position: relative;
}

.cursor {
  display: inline-block;
  width: 2px;
  height: 1em;
  background-color: #67c23a;
  vertical-align: text-bottom;
  margin-left: 1px;
  animation: blink 0.7s infinite;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}

/* 添加加载状态样式 */
.loading-container {
  padding: 20px;
}
</style> 